<template>
	<view>
		<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" multiple :maxCount="maxCount" :accept="accept" v-bind="attrs"></u-upload>
		<!-- <slot name="videos" :prop="fileList">
			<view v-if="accept==='video'">
				<view class="file-view" v-for="(item,index) in fileList" :key="index">
					<view style="flex: 1;">
						<up-text :lines="1" size="12" bold
							:text="item.fileName+item.fileSuffix||upState[item.status]"></up-text>
					</view>
					<view class="p-l-5 p-r-5" v-if="item.downloadUrl||item.status==='success'">
						<up-text size="12" bold type="primary" text="点击查看" @click="prevideo(item)"></up-text>
					</view>
				</view>
				<u-modal :show="modals" title="视频" confirmText="关闭" @confirm="modals=false">
					<view>
						<video :src="videoSrc"></video>
					</view>
				</u-modal>
			</view>
		</slot> -->
	</view>
</template>

<script setup>
import { useAttrs, ref, watch } from 'vue';
import { isEqual } from 'lodash';
import { apiBaseURL } from '@/config/index.js';
import { getAuthorization } from '@/router/auth.js';
const token = getAuthorization('accessToken');

const props = defineProps({
	modelValue: [Array, String],
	maxCount: {
		type: Number,
		default: 10
	},
	accept: {
		type: String,
		default: 'image'
	}
});
let attrs = useAttrs();

const modals = ref(false);
const videoSrc = ref('');
const fileList = ref([]);
const upState = {
	uploading: '上传中',
	failed: '上传失败',
	success: '上传成功'
};
watch(
	() => props.modelValue,
	(val = []) => {
		if (!isEqual(val, fileList.value)) {
			const valData = Array.isArray(val) ? val : [val];

			fileList.value = valData?.map((item) => ({
				id: item.id,
				downloadUrl: item.downloadUrl,
				src: item.downloadUrl,
				url: item.downloadUrl,
				fileName: item.fileName,
				fileSizeFormat: item.fileSizeFormat,
				fileSize: item.fileSize,
				fileSuffix: item.fileSuffix
			}));
		}
	},
	{
		immediate: true
	}
);
const emits = defineEmits(['update:modelValue']);

watch(
	fileList,
	(val) => {
		val.forEach((item) => {
			if (item.message === '成功') emits('update:modelValue', val);
		});
	},
	{
		deep: true
	}
);

// 关闭模态框
function prevideo(e) {
	modals.value = true;
	videoSrc.value = e.downloadUrl;
}

// 删除图片
const deletePic = (event) => {
	fileList.value.splice(event.index, 1);
	emits('update:modelValue', fileList.value);
};

// 新增图片
const afterRead = async (event) => {
	// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	let lists = [].concat(event.file);
	let fileListLen = fileList.value.length;
	lists.map((item) => {
		fileList.value.push({
			...item,
			status: 'uploading',
			message: '上传中'
		});
	});
	for (let i = 0; i < lists.length; i++) {
		uploadFilePromise(lists[i].url).then((result) => {
			const res = JSON.parse(result);
			if (res.code === 200) {
				fileList.value.splice(fileListLen, 1, {
					id: res.data.id,
					downloadUrl: res.data.downloadUrl,
					url: res.data.downloadUrl,
					fileName: res.data.fileName,
					fileSizeFormat: res.data.fileSizeFormat,
					fileSize: res.data.fileSize,
					fileSuffix: res.data.fileSuffix,
					status: 'success',
					message: '成功'
				});
				uni.showToast({
					icon: 'none',
					title: '上传成功'
				});
			} else {
				let item = fileList.value[fileListLen];
				fileList.value.splice(fileListLen, 1, {
					...item,
					status: 'failed',
					message: '失败'
				});
				uni.showToast({
					icon: 'none',
					title: '上传失败'
				});
			}
			fileListLen++;
		});
	}
};

const uploadFilePromise = (url) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: apiBaseURL + '/rdfile/data/upload',
			filePath: url,
			name: 'file',
			header: {
				Authorization: token
			},
			success: (res) => {
				setTimeout(() => {
					resolve(res.data);
				}, 1000);
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
};
</script>

<style scoped lang="scss">
.file-view {
	padding: 10rpx;
	height: 50rpx;
	margin-bottom: 10rpx;
	border-radius: 8rpx;
	display: flex;
	align-items: center;
	background-color: #e7efff;
}
</style>
